package com.renke.server;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.LinkedList;

/**
 * @Description
 * @Auther Z.R.K
 * @Date 2020/12/7 14:41
 **/
@Slf4j
public class JavaNIOServer {

    public static void startNIOServer(Integer port, NIOThread nioThread) {
        try {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.bind(new InetSocketAddress(port));
            ssc.configureBlocking(false); // nonblocking
            log.info("start NIO Server {}", port);
            new Thread(nioThread).start();
            while (true) {
                Thread.sleep(1000);
                SocketChannel client = ssc.accept();

                if (client == null) {
                    log.info("no client");
                } else {
                    client.configureBlocking(true);
                    log.info("client port {}", client.socket().getPort());
                    nioThread.addClient(client);
                }
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
